package controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import utils.UserRoles;


import models.Recommend;
import models.SolutionSubmission;

import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class ajxAddExpertServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try{
			resp.setContentType("text/xml");
			PrintWriter out = resp.getWriter();
	        UserService userService = UserServiceFactory.getUserService();
	        User user = userService.getCurrentUser(); 
	        String user_email = user.getEmail().toLowerCase();
	        String User_Role_String = new UserRoles(user_email).toString();
	        
	        Date today = new java.util.Date();
			
			String SolID = req.getParameter("sol_id");
			if ( SolID == null ){
				resp.sendRedirect("/home.jsp?error=Solution id is null.");
			}
			Long lSolID = Long.parseLong(SolID);
			String comment = req.getParameter("expertComments");

			Objectify ofy = ObjectifyService.begin();
			Query<Recommend> q = ofy.query(Recommend.class).filter("solID", lSolID);
			int recCount = q.countAll();
			
	   		//ADD NEW RATING NOM
			
			Recommend REC = new Recommend();
			REC.setSolID(lSolID);
			REC.setRecommendON(new Date());
			REC.setRecommendBy(user.getEmail());		
			REC.setComment(comment);
			ofy.put(REC);
			
			SolutionSubmission edititem;
			try {				
				
				edititem = ofy.get(SolutionSubmission.class,lSolID);
				edititem.setHasExpert(true);
				edititem.setCountExpert(recCount+1);
				ofy.put(edititem);
				
				UserActionsConnect.AddAction(user_email, "ajxAddExpertServlet", "Edit solID =" + edititem.getSolID(), "Add Expert Comment", User_Role_String, today);
				
			} catch (EntityNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			out.println("Recommendation succesfully Updated!");
		} catch(Exception ee){
			ee.printStackTrace();
		}
	}
}

